$(function () {
    obj.init();
});

var obj = new function () {
    return {
        dataGrid: null,
        dom: {
            search: null
        },
        start: null,
        end:null,
        init: function () {
            this.start = $('#plan_startTime').datebox({disabled: true, width: 95});
            this.end = $('#plan_endTime').datebox({disabled: true, width: 95});
            this.dataGrid = new xhDataGrid($('#list'), 'res/getSchedulePlanData');
            this.dataGrid.parseToolbar().init().activeButton([], ['bt_list_demandStatus', 'bt_list_power', 'bt_list_bookStatus']);
            this.dom.search = $('#bt_list_search');
            xhExtra.clearLoadSuccess(this.dataGrid);
            this.funObj().addCatalogData();//异步加载章节数据
            this.listener();
        },
        listener: function () {
            var $this = this;
            //时间类型
            $('#search_date').combobox({
                valueField:'value',
                textField:'label',
                data: [
                    {label: '--选择时间--', value: ''},
                    {label: '申请开始', value: '0'},
                    {label: '申请结束', value: '1'},
                    {label: '计划开始', value: '2'},
                    {label: '计划结束', value: '3'},
                    {label: '申请开始-结束', value: '4'},
                    {label: '计划开始-结束', value: '5'}],
                onSelect: function(param){
                    var index = $.inArray(param.value, ['0', '1', '2', '3', '4', '5', '6']);
                    var _disabled = true;
                    if (index >= 0) {
                        _disabled = false;
                        var startTime = $this.start.getElementValue(false);
                        var endTime = $this.end.getElementValue(false);
                        $('#plan_startTime').datebox({
                            disabled: _disabled
                        }).datebox(
                            'setValue', startTime
                        );
                        $('#plan_endTime').datebox({
                            disabled: _disabled
                        }).datebox(
                            'setValue', endTime
                        );
                    } else {
                        $('#plan_startTime').datebox({
                            disabled: _disabled
                        });
                        $('#plan_endTime').datebox({
                            disabled: _disabled
                        });
                    }
                }
            });
            //查询
            $this.dom.search.click(function () {
                $this.funObj().search();
            });
            xhTool.bindDocKeyDown($this.dom.search);
            //双击
            this.dataGrid.onDblClickRow = function(rowIndex, rowData){
                var iBookId = rowData['iBookId'];
                var sBookName = rowData['sBookName'];
                var footStr = '<button type="button" class="btn btn-default" data-dismiss="modal" id="bt_modal_close">关闭</button>';
                if (addPower) {
                    footStr = '<button type="button" class="btn btn-primary xh-btn-load" id="plan_form_confirm">保存</button>' + footStr;
                }
                window.top.xhTop.showModal({
                    title: '【排期计划列表】书名：' + sBookName,
                    id: 'plan_form',
                    footerHtml:footStr,
                    content: xhTool.getFrameString('res/applyPlanDetail', {type: 2, bookId: iBookId}, $(window).height()-80),
                    size: 'lg',
                    backClose: false
                });
            };
            //添加
            $('#bt_list_add').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().addPlanApply();
            });
            //需求录入状态
            $('#bt_list_demandStatus').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setDemandStatus();
            });
            //书本录入状态
            $('#bt_list_bookStatus').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setBookStatus();
            });
            //排期查询
            $('#bt_list_planSummary').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setPlanSummary();
            });
            //查看权限
            $('#bt_list_power').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().setSchoolPower();
            });
            //刷新录入状态
            $('#bt_list_refresh').click(function(){
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().refreshPublish();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                //查找
                search: function () {
                    $this.dataGrid.reload({
                        search: {
                            vague: xhExtra.getValue($('#list_vague')),//查询
                            status: xhExtra.getValue($('#search_status')),//申请状态
                            demand_status: xhExtra.getValue($('#search_demand')),//需求录入
                            book_status: xhExtra.getValue($('#search_book')),//书本状态
                            book_subject: xhExtra.getValue($('#search_bookSubject')),//科目
                            book_class: xhExtra.getValue($('#search_bookClass')),//年级
                            new_apply: xhExtra.getValue($('#search_newApply')),//新申请
                            plan_date: $('#search_date').combobox('getValue'),//时间类型
                            startTime: $this.start.getElementValue(false),
                            endTime: $this.end.getElementValue(false)
                        }
                    })
                },
                addCatalogData: function () {
                    $this.dataGrid.onLoadSuccess = function(data){
                        var rows = $this.dataGrid.command('getRows');
                        var idArr = [];
                        $.each(rows, function (index, row) {
                            idArr.push(row.iId);
                            $this.dataGrid.command('updateRow', {index: index, row: {
                                    sDemand: '加载中..'
                                }});
                        });
                        xhExtra.ajaxRequest('res/getCatalogData', {idArr: idArr}, {}, function (data) {
                            if (data) {
                                for (var index in rows) {
                                    index = parseInt(index);
                                    $this.dataGrid.command('updateRow', {
                                        index: index,
                                        row: {
                                            sDemand: data[index]
                                        }
                                    });
                                }
                            }
                        });
                        //end add
                        xhExtra.checkError(data);
                        // $this.dataGrid.clear();
                    };
                },
                addPlanApply: function () {
                    var iBookId = $this.dataGrid.getSelectValues('iBookId');
                    var sBookName = $this.dataGrid.getSelectValues('sBookName');
                    var existBookId = 1;
                    var showMsg = '[排期申请]';
                    if (iBookId.length > 1) {
                        window.top.xhTop.showError('不可同时选择多本书申请');
                        return false;
                    }
                    if (JSON.stringify(iBookId) !== '[]'){
                        existBookId = 2;//选择了书本
                        showMsg = showMsg + '书：' + sBookName;
                    }
                    var footStr = '<button type="button" class="btn btn-default" data-dismiss="modal" id="bt_modal_close">关闭</button>';
                    if (addPower) {
                        footStr = '<button type="button" class="btn btn-primary xh-btn-load" id="schedule_form_confirm">保存</button>' + footStr;
                    }
                    window.top.xhTop.showModal({
                        title: showMsg,
                        id: 'schedule_form',
                        footerHtml: footStr,
                        content: xhTool.getFrameString('res/applyPlanDetail', {type: 3, bookId: iBookId, existBookId: existBookId}, $(window).height()-80),
                        size: 'lg',
                        backClose: false
                    });
                },
                setDemandStatus: function () {
                    var iId = $this.dataGrid.getSelectValue('iId');
                    var iBookId = $this.dataGrid.getSelectValue('iBookId');
                    var sBookName = $this.dataGrid.getSelectValue('sBookName');
                    if (!iBookId) {
                        window.top.xhTop.showError('缺少书id,不可操作');
                        return false;
                    }
                    window.top.swal({
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        title: '填写完成时间',
                        html: '<div><input type="date" id="finishDate" class="swal2-input" style="width: 100%" value="'+xhTool.getNowDate()+'">',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var finishDate     = $('#finishDate', window.top.document).val();
                                if (finishDate < 1){
                                    reject('时间不能为空');
                                } else {
                                    xhExtra.ajaxRequest('res/setDemandStatus', {
                                        id: iId,
                                        bookId: iBookId,
                                        finishDate: finishDate,
                                        status: 1//完成默认为1
                                    }, {success: true});
                                    resolve();
                                    $this.dataGrid.reload();
                                }
                            })
                        }
                    })
                },
                setBookStatus: function () {
                    var iBookId = $this.dataGrid.getSelectValue('iBookId');
                    if (!iBookId) {
                        window.top.xhTop.showError('缺少书id,不可操作');
                        return false;
                    }
                    window.top.swal({
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        title: '设置状态及时间',
                        html: '<div>' +
                        '<select id="status" class="swal2-input">' +
                        '<option value="1">进行中</option>' +
                        '<option value="2">暂停中</option>' +
                        '<option value="3">已完成</option>' +
                        '</select>' +
                        '<input type="date" id="setDate" class="swal2-input" style="width: 100%" value="'+xhTool.getNowDate()+'">',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var status     = $('#status', window.top.document).val();
                                var setDate     = $('#setDate', window.top.document).val();
                                if(!setDate || !status ){
                                    reject('请选择状态和时间');
                                } else {
                                    xhExtra.ajaxRequest('res/setBookStatus', {
                                        bookId: iBookId,
                                        status: status,
                                        setDate: setDate
                                    }, {success: true});
                                    resolve();
                                    $this.dataGrid.reload();
                                }
                            })
                        }
                    })
                },
                setPlanSummary: function () {
                    window.top.xhTop.createNewTab('排期查询', 'res/planSummary');
                },
                setSchoolPower: function () {
                    var iBookId = $this.dataGrid.getSelectValue('iBookId');
                    var sBookName = $this.dataGrid.getSelectValue('sBookName');
                    if (!iBookId) {
                        window.top.xhTop.showError('缺少书id,不可操作');
                        return false;
                    }
                    var footStr = '<button type="button" class="btn btn-default" data-dismiss="modal" id="bt_modal_close">关闭</button>';
                    window.top.xhTop.showModal({
                        title: '【设置可查看权限的学校】书：' + sBookName,
                        footerHtml: footStr,
                        content: xhTool.getFrameString('res/setSchoolPower', {bookId: iBookId}, 460),
                        size: 'md',
                        width: '900',
                        backClose: false
                    });
                },
                refreshPublish: function () {
                    xhExtra.askChangeStatus('res/refreshPlanBookStatus', {}, $this.dataGrid, '确定刷新书本的完成状态？');
                }
            }
        }
    }
};

